package Admin

import (
	"FromNowOnPromote/博客系统/Tblog/controllers"
	"FromNowOnPromote/博客系统/Tblog/models"
	"FromNowOnPromote/博客系统/Tblog/models/User"
	"FromNowOnPromote/博客系统/Tblog/redis"
	"encoding/json"
)

type BanUser struct {
	controllers.MainController
}

type UserData struct {
	Uuid        int
	Username    string
	User_locked int
	IconUrl     string
}

func (this *BanUser) SendUserData() {
	uuid := this.Ctx.GetCookie("uuid")
	rd := redis.R.Conn
	defer rd.Close()
	AdminId, err1 := rd.Get(uuid)
	if AdminId == "" || err1 != nil {
		body := map[string]interface{}{"code": 300, "data": "验证失败", "msg": "管理员账号不存在"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	//推送用户数据
	db := models.ConnDb()
	defer db.Close()
	var ud []UserData
	err2 := db.Raw("select * from tbuser").Scan(&ud).Error
	if err2 != nil {
		body := map[string]interface{}{"code": 301, "msg": "服务器异常"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	body := map[string]interface{}{"code": 200, "data": ud}
	this.Data["json"] = body
	this.ServeJSON()
}

type BanResp struct {
	Uuid        int `json:"uuid"`
	User_locked int `json:"locked"`
}

func (this *BanUser) BanUser() {
	uuid := this.Ctx.GetCookie("uuid")
	rd := redis.R.Conn
	defer rd.Close()
	AdminId, err1 := rd.Get(uuid)
	if AdminId == "" || err1 != nil {
		body := map[string]interface{}{"code": 300, "data": "验证失败", "msg": "管理员账号不存在"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	var br BanResp
	r := this.Ctx.Request
	decoder := json.NewDecoder(r.Body)
	err2 := decoder.Decode(&br)
	if err2 != nil {
		body := map[string]interface{}{"code": 301, "data": "服务器异常"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	//更新数据库用户状态字段
	db := models.ConnDb()
	defer db.Close()
	var tbuser User.TbUser
	err3 := db.Model(&tbuser).Where("uuid = ?", br.Uuid).Update(map[string]interface{}{"User_locked": br.User_locked}).Error
	if err3 != nil {
		body := map[string]interface{}{"code": 302, "data": "服务器异常"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	body := map[string]interface{}{"code": 200, "data": "操作成功"}
	this.Data["json"] = body
	this.ServeJSON()
	return
}
